package com.gl.emms.whale.ui;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.AlertDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.CursorAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;

import com.gl.emms.client.android.EMMSPushManager;
import com.gl.emms.nio.mutual.ReplyBody;
import com.gl.emms.whale.R;
import com.gl.emms.whale.R.string;
import com.gl.emms.whale.app.Constant;
import com.gl.emms.whale.app.MyApplication;
import com.gl.emms.whale.app.WhaleMonitorActivity;
import com.gl.emms.whale.util.Alarm;
import com.gl.emms.whale.util.Alarms;
import com.gl.emms.whale.util.DialogFactory;
import com.gl.emms.whale.util.SharePreferenceUtil;
import com.gl.emms.whale.util.SystemMsgEntity;
import com.gl.emms.whale.util.TimingControlEntity;

/**阀门定时控制界面类
 * @author ganlinux
 *
 */
public class ValveAutoControlActivity extends WhaleMonitorActivity implements
OnItemClickListener,TimePickerDialog.OnTimeSetListener,OnClickListener{
	Timer timer;//定时器
	
	private ListView mAlarmsList;//控制选择控件
	private int mHour;//保存选择的小时
	private int mMinutes;//保存选择的分钟
	private String[] controlTime ,controlType;//控制时间，控制方式
	private boolean[] controlEnable;//控制使能存储
	private TimingControlAdapter adapter;//控制适配器
	private List<TimingControlEntity> timingControlEntities  = null;

	private int currentPosition;//记录当前位置
	
	SharePreferenceUtil util ;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
		setContentView(R.layout.activity_valveautocontrol);

		//初始化界面
		initViews();
	}

	/**
	 * 初始化界面
	 * @time 2014年11月12日下午1:19:45
	 * @return void
	 * @user ganlinux
	 */
	public void initViews() {
		
		controlTime = new String[4];
		controlType = new String[4];
		//返回按钮
		Button titleBackBtn = (Button)findViewById(R.id.TitleBackBtn);  
		titleBackBtn.setOnClickListener(this);

		mAlarmsList = (ListView) findViewById(R.id.alarms_list);
		util = new SharePreferenceUtil(this, Constant.SAVE_SYSTEMSETTING);
		for (int i = 0; i < 4; i++) {
			controlEnable = util.getAutoControlEnable();
			
			controlType = util.getAutoControlType();
			
			controlTime = util.getAutoControlTime();
		}
		
		
		timingControlEntities = new ArrayList<TimingControlEntity>();
		TimingControlEntity timingControlEntity1 = new TimingControlEntity(1, controlTime[0], controlType[0], controlEnable[0]);
		TimingControlEntity timingControlEntity2 = new TimingControlEntity(2, controlTime[1], controlType[1], controlEnable[1]);
		TimingControlEntity timingControlEntity3 = new TimingControlEntity(3, controlTime[2], controlType[2], controlEnable[2]);
		TimingControlEntity timingControlEntity4 = new TimingControlEntity(4, controlTime[3], controlType[3], controlEnable[3]);
		timingControlEntities.add(timingControlEntity1);
		timingControlEntities.add(timingControlEntity2);
		timingControlEntities.add(timingControlEntity3);
		timingControlEntities.add(timingControlEntity4);
		adapter = new TimingControlAdapter(this, timingControlEntities);
		mAlarmsList.setAdapter(adapter);
		mAlarmsList.setVerticalScrollBarEnabled(true);
		mAlarmsList.setOnCreateContextMenuListener(this);
		
	}

	/**
	 * 类：定时控制适配器
	 * @author ganlinux
	 *
	 */
	private class TimingControlAdapter extends BaseAdapter {

		private ValveAutoControlActivity context;
		private List<TimingControlEntity> list;// 消息对象数组
		private LayoutInflater inflater;
		public TimingControlAdapter(ValveAutoControlActivity context, List<TimingControlEntity> list) {
			this.context = context;
			this.list = list;
			inflater = LayoutInflater.from(context);
		}

		public int getCount() {
			return list.size();
		}

		public Object getItem(int position) {
			return list.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(final int position, View convertView, ViewGroup parent) {

			ViewHolder viewHolder;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.item_controlswitch, null);
				viewHolder = new ViewHolder();
				viewHolder.indicator = convertView.findViewById(R.id.indicator);

				// Set the initial resource for the bar image.
				final ImageView barOnOff = (ImageView) convertView.findViewById(R.id.bar_onoff);
				// Set the initial state of the clock "checkbox"
				final CheckBox clockOnOff = (CheckBox) convertView.findViewById(R.id.clock_onoff);

				// Clicking outside the "checkbox" should also change the state.
				//对checkbox设置监听，使里外一致
				
				clockOnOff.setOnCheckedChangeListener(new OnCheckedChangeListener() {
					
					@Override
					public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
						// TODO Auto-generated method stub
						controlEnable[position] = clockOnOff.isChecked();
						controlSwitch(controlEnable[position],barOnOff);
						
					}
				});
				clockOnOff.setChecked(controlEnable[position]);
				controlSwitch(controlEnable[position],barOnOff);
				viewHolder.indicator.setOnClickListener(new OnClickListener() {
					
					public void onClick(View v) {
						clockOnOff.toggle();
						
						//controlSwitch(clockOnOff.isChecked(),barOnOff);
						//controlEnable[position] = clockOnOff.isChecked();
						//controlSwitch(controlEnable[position],barOnOff);
						//
					}
				});
				
				viewHolder.time = (TextView) convertView.findViewById(R.id.timeDisplay);

				viewHolder.time.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {
						currentPosition = position;
						showTimePicker();
					}
				});
				viewHolder.type = (TextView) convertView
						.findViewById(R.id.controltype);
				viewHolder.type.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {
						currentPosition = position;
						showControlTypeChoose();
					}
				});
				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}
			if(list.isEmpty())
			{

			}else
			{
				//clockOnOff.ser
				//viewHolder.indicator.setEnabled(list.get(position).getIsEnable());
				//ImageView barOnOff = (ImageView) convertView.findViewById(R.id.bar_onoff);
				//controlSwitch(controlEnable[position],barOnOff);
				//viewHolder.time.setText(list.get(position).getTime());
				//viewHolder.type.setText(list.get(position).getType());
				viewHolder.time.setText(controlTime[position]);
				if (controlType[position].equals("1")) {
					viewHolder.type.setText("控制开");
				}else if (controlType[position].equals("0")) {
					viewHolder.type.setText("控制关");
				}else {
					viewHolder.type.setText("未设置");
				}
			}
			return convertView;
		}

		class ViewHolder {
			public View indicator;
			public TextView time;
			public TextView type;
		}
	};
	/**
	 * 控制开关
	 * @time 2014年11月12日下午1:28:19
	 * @return void
	 * @param enabled
	 * @param bar
	 * @user ganlinux
	 */
	private void controlSwitch(boolean enabled,ImageView bar) {
		bar.setImageResource(enabled ? R.drawable.ic_indicator_on
				: R.drawable.ic_indicator_off);
	}
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
	}
	/**
	 * 显示时间选择器
	 * @time 2014年11月12日下午1:28:33
	 * @return void
	 * @user ganlinux
	 */
	private void showTimePicker() {
		new TimePickerDialog(this, this, mHour, mMinutes,
				DateFormat.is24HourFormat(this)).show();
	}
	/**
	 * 显示控制类型选择
	 * @time 2014年11月12日下午1:28:48
	 * @return void
	 * @user ganlinux
	 */
	private void showControlTypeChoose() {
		final CharSequence[] items = { getText(R.string.control_on), getText(R.string.control_off)};
		AlertDialog imageDialog = new AlertDialog.Builder(this)
		.setTitle(getText(R.string.control_alert_title))
		.setIcon(android.R.drawable.btn_star)
		.setItems(items, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {
				
				switch (currentPosition) {
				case 0:
					if (item == 0) {
						controlType[0] = "1";
					}else if (item == 1) {
						controlType[0] = "0";
					}
					
					break;
				case 1:
					if (item == 0) {
						controlType[1] = "1";
					}else if (item == 1) {
						controlType[1] = "0";
					}
					break;
				case 2:
					if (item == 0) {
						controlType[2] = "1";
					}else if (item == 1) {
						controlType[2] = "0";
					}
					break;
				case 3:
					if (item == 0) {
						controlType[3] = "1";
					}else if (item == 1) {
						controlType[3] = "0";
					}
					break;

				default:
					break;
				}
				adapter.notifyDataSetChanged();
			}
		}).create();
		imageDialog.show();
	}

	@Override
	public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
		// onTimeSet is called when the user clicks "Set"
		mHour = hourOfDay;
		mMinutes = minute;

		//TimingControlAdapter.this.viewHolder.time.setText(mHour+":"+mMinutes);
		switch (currentPosition) {
		case 0:
			controlTime[0] = getString(R.string.control_time, mHour,mMinutes);
			break;
		case 1:
			controlTime[1] = getString(R.string.control_time, mHour,mMinutes);
			break;
		case 2:
			controlTime[2] = getString(R.string.control_time, mHour,mMinutes);
			break;
		case 3:
			controlTime[3] = getString(R.string.control_time, mHour,mMinutes);
			break;

		default:
			break;
		}
		adapter.notifyDataSetChanged();
		// If the time has been changed, enable the alarm.
		// Save the alarm and pop a toast.
	}
	/**
	 * 发送控制信息
	 * @time 2014年11月12日下午1:29:20
	 * @return void
	 * @param target
	 * @user ganlinux
	 */
	public void sendControl(View target){
		
		util.setAutoControl(controlEnable, controlTime, controlType);
		showProgressDialog("提示", "正在设置定时控制，请稍后......");
		EMMSPushManager.requestAutoForceControl(this,MyApplication.getUserData().getIdIP(),MyApplication.getUserData().getMainroom(),controlEnable,controlTime,controlType);
		//startTimer(30);
	}
	public void startTimer(int secends){

		TimerTask task = new TimerTask(){   
			public void run() {
				timerCancle();
				timerStop();
			}   
		};
		timer = new Timer(true);  
		timer.schedule(task,secends*1000);
	}
	public void timerCancle(){
		timer.cancel();
	}
	public void timerStop(){
		Message message = new Message();      
		message.what = 0x02;      
		handler.sendEmptyMessage(message.what);
	}
	Handler handler = new Handler(){  
		public void handleMessage(Message msg) {  
			switch (msg.what) {      
			case 0x02: 
				hideProgressDialog();
				DialogFactory.ToastDialog(ValveAutoControlActivity.this,"阀门定时控制",
						"失败，通讯失败，请重试");
				break;      
			}      
			super.handleMessage(msg);  
		}    
	}; 
	@Override
	public void onReplyReceived(final ReplyBody reply) {
		super.onReplyReceived(reply);
		if (reply.getType().equals(Constant.TYPE_AUTOCONTROL_RESPONSE)) {
			hideProgressDialog();
			//timerCancle();
			if (reply.get("controlstate").equals("000000")) {
				DialogFactory.ToastDialog(ValveAutoControlActivity.this,"阀门定时控制",
						"成功");
			}else {
				DialogFactory.ToastDialog(ValveAutoControlActivity.this,"阀门定时控制",
						"失败");
			}
			
		}

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.TitleBackBtn:
			//timerCancle();
			new KeyEvent(KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_BACK);
			finish();
			break;

		default:
			break;
		}
	}
	@Override
	public void onConnectionSucceed()//重连由loginactivity 负责
	{
	}
	@Override
	public void onConnectionStatus(boolean  isConnected){}//网络状态改变由loginactivity 负责
	@Override
	public   void onNetworkChanged(NetworkInfo info){
	};
}